package com.gitee.neuray.security.modules.param.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.util.*;

public class ExcelUtil {

    public static void main(String[] args)throws Exception {
        String [] arr = {"表头1","表头2","表头3","表头4"};
        Map param = new HashMap();
        param.put("fields", Arrays.asList(arr));
        param.put("filePath","C:\\Users\\zjt\\Desktop\\test.xlsx");
//        process(param);
    }

    public static void process(OutputStream out, Map param) throws Exception {
//        FileOutputStream out = new FileOutputStream(param.get("filePath").toString());
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        SXSSFSheet sheet = workbook.createSheet("参数信息");

        //表头cell格式
        CellStyle FirstRowCellStyle = workbook.createCellStyle();
        FirstRowCellStyle.setAlignment(HorizontalAlignment.CENTER);
        Font font = workbook.createFont();
        font.setBold(true);
        FirstRowCellStyle.setFont(font);

        CellStyle css = workbook.createCellStyle();
        DataFormat format = workbook.createDataFormat();
        css.setDataFormat(format.getFormat("@"));

        //生成第一行表头
        List<String> fieldsMappingFirstRow = (List<String>) param.get("fieldsName");
        SXSSFRow firstRow = sheet.createRow(0);
        for (int i = 0; i < fieldsMappingFirstRow.size(); i++) {
            //列宽
            sheet.setColumnWidth(i,15*256);
            SXSSFCell cell = firstRow.createCell(i);
            cell.setCellStyle(FirstRowCellStyle);
            cell.setCellValue(fieldsMappingFirstRow.get(i));
            sheet.setDefaultColumnStyle(i,css);
        }


        //表头以外的cell格式
        CellStyle rowCellStyle = workbook.createCellStyle();
        rowCellStyle.setAlignment(HorizontalAlignment.CENTER);
        if(param.get("data") != null){
            //查询所有的字段映射数据
            List<Map> list = (List<Map>) param.get("data");
            List<String> fields = (List<String>) param.get("fields");
            for(int a = 0;a < list.size();a++){
                SXSSFRow row = sheet.createRow(a+1);
                for (int i = 0; i <fields.size() ; i++) {
                    SXSSFCell cell= row.createCell(i);
                    cell.setCellStyle(rowCellStyle);
                    cell.setCellValue(list.get(a).get(fields.get(i).toString()).toString());
                }
            }
        }
        workbook.write(out);
        workbook.close();
        //清理临时文件
        workbook.dispose();
    }
}
